package com.xiyou.week02.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 811. 子域名访问计数
 *
 * @ClassName：SubdomainVisits
 * @Author：西柚
 * @Date：2022/1/9 11:36 下午
 * @Versiion：1.0
 */
public class SubdomainVisits {

    /**
     * 输入：cpdomains = ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
     * 输出：["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
     * 解释：按照前文描述，会访问 "google.mail.com" 900 次，"yahoo.com" 50 次，"intel.mail.com" 1 次，"wiki.org" 5 次。
     * 而对于父域名，会访问 "mail.com" 900 + 1 = 901 次，"com" 900 + 50 + 1 = 951 次，和 "org" 5 次。
     *
     * @param cpdomains
     * @return
     */
    public static List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> counts = new HashMap<String, Integer>();
        for (String cpdomain : cpdomains) {
            // 将cpdomains数组中的每个字符串的出现字数和地址分隔开
            String[] cpinfo = cpdomain.split(" ");
            // 将地址中的每个子域名分隔开
            String[] frags = cpinfo[1].split("\\.");
            // count为地址出现次数
            int count = Integer.valueOf(cpinfo[0]);
            String cur = "";
            for (int i = frags.length - 1; i >= 0; --i) {
                if (i < frags.length - 1) {
                    cur = frags[i] + "." + cur;
                } else {
                    cur = frags[i] +  cur;
                }
                counts.put(cur, counts.getOrDefault(cur, 0) + count);
            }
        }

        List<String> ans = new ArrayList<>();
        for (String dom : counts.keySet()) {
            ans.add(counts.get(dom) + " " + dom);
        }
        return ans;
    }

    public static void main(String[] args) {
        String[] cpdomains = {"900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"};
        System.out.println(subdomainVisits(cpdomains));
    }
}
